package com.stn.zjx.givingtreasure.activity.address;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.adapter.AddressManagerItemListAdapter;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.domain.UserAddressDomain;
import com.stn.zjx.givingtreasure.event.AddressEvent;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.UserAddressNetImpl;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.table.User;
import com.vondear.rxtools.RxActivityTool;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AddressManagerActivity extends BaseActivity {
    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.sure_bt)
    TextView sureBt;
    @BindView(R.id.share_bt)
    RelativeLayout shareBt;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.add_white)
    ImageView addWhite;
    @BindView(R.id.bottom)
    RelativeLayout bottom;
    @BindView(R.id.twinkling_refresh)
    TwinklingRefreshLayout twinklingRefresh;
    Integer pageNow = 1;
    Integer pageSize = 10;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    private boolean isMoreLoading = false;
    private int visibleItemCount = 0;
    private LinearLayoutManager lm;
    private AddressManagerItemListAdapter adapter;

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Override
    public void initComponent() {
        actionTitle.setText(getString(R.string.add_address));
        rv.setLayoutManager(lm = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false));
        rv.setAdapter(adapter = new AddressManagerItemListAdapter(this));
        ProgressLayout headerView = new ProgressLayout(this);
        headerView.setColorSchemeResources(R.color.colorAccent);
        twinklingRefresh.setHeaderView(headerView);
        twinklingRefresh.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                initRefresh();
            }

            @Override
            public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {

            }
        });

        rv.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (isMoreLoading == false && newState == RecyclerView.SCROLL_STATE_IDLE && visibleItemCount == adapter.dataBeanList.size() - 1 &&
                        adapter.dataBeanList.size() >= pageNow * 10) {
                    initAppend();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                visibleItemCount = lm.findLastVisibleItemPosition();
            }
        });
        twinklingRefresh.startRefresh();

    }
  @Subscribe(threadMode = ThreadMode.MAIN)
  public void onEvent(AddressEvent event){
        switch (event.flag){
            case 1:
                twinklingRefresh.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        twinklingRefresh.setEnableRefresh(true);
                        initRefresh();
                    }
                }, 200);
                break;
        }
  }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address_manager);
        ButterKnife.bind(this);
        initComponent();
    }

    @OnClick({R.id.back_bt,R.id.add_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;
            case R.id.add_address:
                RxActivityTool.skipActivity(this,AddAddressActivity.class);
                break;

        }
    }

    public void initRefresh() {
        User userOnline = UserService.getInstance(getApplicationContext()).getOnlineLoginUser();
        if (userOnline == null) {
            twinklingRefresh.finishRefreshing();
            return;
        }
        pageNow = 1;
        UserAddressNetImpl
                .query_user_address(pageNow, pageSize, userOnline.getToken(), userOnline.getUserId() + "_query_user_address",
                        new StringCallback() {
                            @Override
                            public void onFinish() {
                                super.onFinish();
                                twinklingRefresh.finishRefreshing();
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                if (response.isSuccessful() && !isFinishing()) {
                                    UserAddressDomain domain = new Gson().fromJson(response.body(), UserAddressDomain.class);
                                    switch (domain.getStatus()) {
                                        case BaseApi.REQUEST_SUCCESS_CODE:
                                            if (domain.getData() != null && domain.getData().size() != 0) {
                                                 noDataTv.setVisibility(View.GONE);
                                                adapter.refreshList(domain.getData());

                                            }else{
                                                noDataTv.setVisibility(View.VISIBLE);
                                                adapter.clearList();
                                            }
                                            break;
                                         default:
                                             noDataTv.setVisibility(View.VISIBLE);
                                             adapter.clearList();
                                             break;
                                    }
                                }
                            }

                            @Override
                            public void onCacheSuccess(Response<String> response) {
                                super.onCacheSuccess(response);
                                if (response.isSuccessful() && !isFinishing()) {
                                    UserAddressDomain domain = new Gson().fromJson(response.body(), UserAddressDomain.class);
                                    switch (domain.getStatus()) {
                                        case BaseApi.REQUEST_SUCCESS_CODE:
                                            if (domain.getData() != null && domain.getData().size() != 0) {
                                                noDataTv.setVisibility(View.GONE);
                                                adapter.refreshList(domain.getData());

                                            }else{
                                                noDataTv.setVisibility(View.VISIBLE);
                                                adapter.clearList();
                                            }
                                            break;
                                        default:
                                            noDataTv.setVisibility(View.VISIBLE);
                                            adapter.clearList();
                                            break;
                                    }
                                }
                            }
                        });
    }

    public void initAppend() {
        User userOnline = UserService.getInstance(getApplicationContext()).getOnlineLoginUser();
        if (userOnline == null) {
            isMoreLoading = false;
            return;
        }
        pageNow++;
        UserAddressNetImpl
                .query_user_address(pageNow, pageSize, userOnline.getToken(), userOnline.getUserId() + "_query_user_address",
                        new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                                isMoreLoading=true;
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                isMoreLoading = false;
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                if (response.isSuccessful() && !isFinishing()) {
                                    UserAddressDomain domain = new Gson().fromJson(response.body(), UserAddressDomain.class);
                                    switch (domain.getStatus()) {
                                        case BaseApi.REQUEST_SUCCESS_CODE:
                                            if (domain.getData() != null && domain.getData().size() != 0) {
                                                adapter.appendList(domain.getData());
                                            }
                                            break;
                                    }
                                }
                            }
                        });
    }
}
